package com.rzt.cft.api.config;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * WebConfig
 *
 * @author zz
 * 2019/11/5
 */
@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 请求日志接口，暂时不开启
     * @return

     @Order(1)
     @Bean public Filter logFilter(){
     return new LogFilter();
     }
     */

     /**
      * jackson转换器
      * 解决LocalDateTime序列化返回带T的问题
      * @return
      */
     @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
     private String pattern;

     @Bean
     public LocalDateTimeSerializer localDateTimeDeserializer() {
          return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
     }

     @Bean
     public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
          return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
     }

     /**
      * 处理跨域
      * @return
      */
//     @Bean
//     public CorsFilter corsFilter() {
//          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//          source.registerCorsConfiguration("/**", buildConfig());
//          // 4
//          return new CorsFilter(source);
//     }

     @Bean
     public FilterRegistrationBean corsFilter() {
          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
          CorsConfiguration config = new CorsConfiguration();
          config.setAllowCredentials(true);
          config.addAllowedOrigin("*");
          config.addAllowedHeader("*");
          config.addAllowedMethod("*");
          source.registerCorsConfiguration("/**", config); // CORS 配置对所有接口都有效
          FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
          bean.setOrder(0);
          return bean;
     }

     private CorsConfiguration buildConfig() {
          CorsConfiguration corsConfiguration = new CorsConfiguration();
          corsConfiguration.addAllowedOrigin("*");
          // 1允许任何域名使用
          corsConfiguration.addAllowedHeader("*");
          // 2允许任何头
          corsConfiguration.addAllowedMethod("*");
          // 3允许任何方法（post、get等）
          return corsConfiguration;
     }
}
